﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Collections.Generic;

namespace Jy123.Web.home
{
    public partial class index :System.Web.UI.Page //Web.AppBasePage.User 
    {
        protected int userID;//用户ID
        protected int accessUserID;//访问者ID
        protected int pagesize = 8;
        protected int cpage = 1;//当前页
        protected List<int?> count;
        protected void Page_Load(object sender, EventArgs e)
        {
            //读取Cookie中的用户信息
            string strUserIdFromCookie = Common.Cookie.getCookie("UserID");
            if (string.IsNullOrEmpty(strUserIdFromCookie))
            {
                Response.Redirect("/");//当Cookie中没有用户信息则跳转到用户登陆页
            }
            accessUserID = int.Parse(strUserIdFromCookie);
            string strUserID = Request.QueryString["UserID"];//作者ID

            if (!string.IsNullOrEmpty(strUserID)) //当查询作者ID不为空时
            {
                userID = Convert.ToInt32(strUserID);
                if (strUserID == accessUserID.ToString())
                {
                    Response.Redirect("/home/");
                }
                else
                {
                    InsertVisitRecord(userID, accessUserID);//更新访问记录
                }
            }
            else  //当查询作者的ID为空时，就默认查自己
            { userID = accessUserID; }

            string strmoodContent = Request.Form["moodContent"];
            
            //更新心情
            if (!string.IsNullOrEmpty(strmoodContent))
            {
                Jy123.Model.User_Mood mMood = new Jy123.Model.User_Mood();
                mMood.FUser=userID;
                mMood.MoodContent =Common.Input.GetSubString(strmoodContent,60);
                //mMood.MoodContent = strmoodContent;

                mMood.PostTime = DateTime.Now;
                mMood.PostIP = Common.Public.GetClientIP();
                mMood.IsLock=false;
                mMood.Comments=0;
                mMood.isRec=0;
                new Jy123.BLL.User_Mood().Add(mMood);
            }

            //页面初始化
            StringBuilder indexHtml = new StringBuilder(Cache["user_index"].ToString());//最终写出页面的大sb
            string strHeader = Cache["user_header"].ToString();
            strHeader = strHeader.Replace("$UserID$",userID.ToString());
            indexHtml = indexHtml.Replace("$Header$",strHeader);//头部
            indexHtml = indexHtml.Replace("$Footer$", Cache["user_footer"].ToString());//底部
            indexHtml = indexHtml.Replace("$LeftUserCmd$", Cache["user_navigation_up"].ToString());//左侧导航
            indexHtml = indexHtml.Replace("$LeftUserFriendAdd$", Cache["user_friendadd"].ToString());//左侧直接添加好友
            indexHtml.Replace("$FaceList$", new Jy123.BLL.User.UserSql().FaceList(Cache["user_face"].ToString()));//初始化表情列表
            //用户信息栏
            Jy123.Model.User_Main modelUser = new Jy123.Model.User_Main();
            Jy123.BLL.User_Main bllUser = new Jy123.BLL.User_Main();
            modelUser = bllUser.GetModel(userID);


            //根据用户ID判断用户是否有头像,如果没有头像就返回默认头像地址
            modelUser.Portrait = new Jy123.BLL.User.SPace().DefaultPortrait(userID);

            bool takePic = new AppCode.CreateDir().EqualWH(modelUser.Portrait, 100, 100);
            if (takePic) 
            {                
                indexHtml.Replace("$UserHead$", new AppCode.CreateDir().ReDraw(100, 100, modelUser.Portrait)); 
            }
            else {indexHtml.Replace("$UserHead$", modelUser.Portrait);}
           
            //indexHtml.Replace("$UserName$", Common.Input.GetSubString(modelUser.UserName,6));
            //来访者列表
            indexHtml.Replace("$VisitIn_ul$", ListVisitIn(userID));
            
            // 可能认识的人
            if (accessUserID == userID)
            {
                indexHtml.Replace("$user_congnition$", ListCongnition(accessUserID));
            }
            else
            {
                indexHtml.Replace("$user_congnition$", "");
            }
            
            #region 我的消息栏or好友的消息栏
            //判断性别
            bool isGirl;
            string strFrdList = string.Empty;
            if (accessUserID != userID)
            {
                Jy123.Model.User_Info mUserInfo = new Jy123.Model.User_Info();
                Jy123.BLL.User_Info bllUserInfo = new Jy123.BLL.User_Info();
                mUserInfo = mUserInfo = bllUserInfo.GetModel(userID);
                isGirl = mUserInfo.Sex;
                indexHtml = indexHtml.Replace("$MyFriendList_ul$", PageFriendList_He_She(userID, indexHtml, isGirl));
                //别人信息
                string strUserInfo = Cache["user_index_userinfo_other"].ToString();
                Jy123.BLL.Module.Module bllModule = new Jy123.BLL.Module.Module();
                int userAllMoney = bllModule.GetUserAllMoney(modelUser);
                strUserInfo = strUserInfo.Replace("$UserName$", Common.Input.GetSubString(modelUser.UserName, 8))
                    .Replace("$Occupation$",new Jy123.BLL.User.SPace().UserLevel(userAllMoney));
                indexHtml = indexHtml.Replace("$UserInfo$",strUserInfo);
                indexHtml = indexHtml.Replace("$MiniContentUserID$", "?MiniContentUserID="+userID.ToString());

                //别人消息
                string strUserMsg = Cache["user_index_usermsg_other"].ToString();
                //int albumCount,blogCount,giftCount;

                strUserMsg = strUserMsg.Replace("$PhotoMsg$", new Jy123.BLL.User.Album().PhotoCountByUserID(userID).ToString());
                strUserMsg = strUserMsg.Replace("$BlogMsg$", new Jy123.BLL.User.Blog().BlogCount(userID).ToString());
                strUserMsg = strUserMsg.Replace("$GiftMsg$", new Jy123.BLL.User.Gift().CountReceiveGift(userID).ToString());
                strUserMsg = strUserMsg.Replace("$VoteMsg$", new Jy123.BLL.User.Vote().GetVoteListCountByUserID(userID).ToString());
                indexHtml = indexHtml.Replace("$UserMsg$",strUserMsg);
                indexHtml = indexHtml.Replace("好友动态", "他的动态");

                //别人的头像地址
                indexHtml = indexHtml.Replace("$userID$", userID.ToString());
                //个人心情
                string strMoodContent = new Jy123.BLL.User.Mood().GetUserMoodContentByID(userID);
                if (!string.IsNullOrEmpty(strMoodContent))
                { indexHtml.Replace("$MoodContent$", Jy123.BLL.User.UserSql.BlogContent(Common.Input.GetSubString(strMoodContent,32))); }
                else
                { indexHtml.Replace("$MoodContent$", "目前无心情！"); }
                indexHtml.Replace("<li><a href='#'>编辑</a></li>",string.Empty);
                indexHtml.Replace("个人档案",modelUser.UserName+"的档案");
            }
            else
            {
                indexHtml = indexHtml.Replace("$MyFriendList_ul$", PageMyFriendList(userID, indexHtml));
                //自己的信息
                string strUserInfo = Cache["user_index_userinfo"].ToString();
                strUserInfo = strUserInfo.Replace("$UserName$", Common.Input.GetSubString(modelUser.UserName, 8));
                Jy123.BLL.Module.Module bllModule = new Jy123.BLL.Module.Module();
                int userAllMoney = bllModule.GetUserAllMoney(modelUser);

                strUserInfo = strUserInfo.Replace("$Occupation$",new Jy123.BLL.User.SPace().UserLevel(userAllMoney));
                int nextLevelMoney = 0;
                //string strnextLevelMoney = new Jy123.BLL.User.SPace().NextLevelMoney(userAllMoney);
                nextLevelMoney = new Jy123.BLL.User.SPace().NextLevelMoney(userAllMoney);
                if (nextLevelMoney > userAllMoney)
                {
                    strUserInfo = strUserInfo.Replace("$UpgradePoint$", (nextLevelMoney - userAllMoney).ToString());
                }
                else
                {
                    //strUserInfo = strUserInfo.Replace("离下一级还差：￥$UpgradePoint$", "暂未开放更高等级");
                    strUserInfo = strUserInfo.Replace("离下一级还差：<br />￥$UpgradePoint$", "暂未开放更高等级");
                }
                indexHtml = indexHtml.Replace("$UserInfo$", strUserInfo);
                indexHtml = indexHtml.Replace("$MiniContentUserID$","");
                //自己的消息
                indexHtml = indexHtml.Replace("$UserMsg$", Cache["user_index_usermsg"].ToString());
                //自己的头像地址
                indexHtml = indexHtml.Replace("?userID=$userID$", "");
                
                //个人心情
                string strMoodContent =  new Jy123.BLL.User.Mood().GetUserMoodContentByID(userID);
                if (!string.IsNullOrEmpty(strMoodContent))
                { indexHtml.Replace("$MoodContent$", Jy123.BLL.User.UserSql.BlogContent(Common.Input.GetSubString(strMoodContent, 32))); }
                else
                { indexHtml.Replace("$MoodContent$", "目前无心情！");}
            }
            #endregion
            #region 统计站内信数量
            Jy123.BLL.User.Letter bllLetter = new Jy123.BLL.User.Letter();
            //站内信
            int newLetterCount = bllLetter.CountNewLetter(userID);
            indexHtml = indexHtml.Replace("$NewMsg$", newLetterCount.ToString());
            //通知
            int newNoticeCount = bllLetter.CountNewNotice();
            indexHtml.Replace("$NewNotice$",newNoticeCount.ToString());
            //礼物数
            string newGiftCount = new Jy123.BLL.User.Gift().CountReceiveGift(userID);
            indexHtml.Replace("$NewGift$",newGiftCount);
            #endregion
            #region 加为好友or等待确认
            int isRequested = new BLL.User.Friend().AlreadySearch(accessUserID, userID);
            if (strUserID == accessUserID.ToString())
            {
                Response.Redirect("/home/");
            }
            switch (isRequested)
            {
                case 2:
                    indexHtml = indexHtml.Replace("$MsgOther_A$",
                    string.Format("<span><a href=\"javascript:;\" onclick =\"myAjax('/home/FriendAddByUserID.ashx','UserID={0}');$(this).parent().html('<span class=red>等待确认</span>');\">加为好友</a></span>", userID));
                    break;
                case 1:
                    indexHtml = indexHtml.Replace("$MsgOther_A$", "");
                    break;
                case 0:
                    indexHtml = indexHtml.Replace("$MsgOther_A$", "<span class='red'>等待确认</span>");
                    break;
            }
            #endregion
            //好友请求数量
            indexHtml = indexHtml.Replace("$NewSysMsg$",new Jy123.BLL.User.Friend().CountFriendRequest(userID).ToString());
            Response.Write(indexHtml.ToString());
        }
        /// <summary>
        /// 插入访问记录
        /// </summary>
        /// <param name="userID">被访问者的ID</param>
        /// <param name="AccessID">访问者ID</param>
        private void InsertVisitRecord(int userID,int AccessID)
        {
            //插入一个访问记录
            Jy123.BLL.User_Visit bllVisit = new Jy123.BLL.User_Visit();
            List<Jy123.Model.User_Visit> mVisits = bllVisit.GetModelList("FUser='" + userID + "'and FUserVisitor='" + accessUserID + "'");
            if (mVisits.Count != 0)
            {
                mVisits[0].LastVisitTime = DateTime.Now;
                mVisits[0].VisitTimes += 1;
                bllVisit.Update(mVisits[0]);
            }
            else
            {
                Jy123.Model.User_Visit mVisit = new Jy123.Model.User_Visit();
                mVisit.FUser = userID;
                mVisit.FUserVisitor = accessUserID;
                mVisit.LastVisitTime = DateTime.Now;
                mVisit.LastVisitIP = Common.Public.GetClientIP();
                mVisit.VisitTimes = 1;
                bllVisit.Add(mVisit);
            }
        }
        /// <summary>
        /// 来访者列表
        /// </summary>
        /// <param name="userID">被访问者ID</param>
        /// <returns>string</returns>
        private string ListVisitIn(int userID)
        {
            string strVisitIn_ul = Cache["user_VisitIn_ul"].ToString();
            Jy123.BLL.User.Friend bllUserFrd = new Jy123.BLL.User.Friend();
            DataTable dtFrdIn = bllUserFrd.FriendGetVisitList_In(cpage, pagesize, userID, out count).Tables[0];
            StringBuilder strli = new StringBuilder();
            for (int i = 0; i < dtFrdIn.Rows.Count; i++)
            {
                //根据用户ID判断用户是否有头像,如果没有头像就返回默认头像地址
                string userPortrait = new Jy123.BLL.User.SPace().DefaultPortrait(Convert.ToInt32(dtFrdIn.Rows[i]["FUserVisitor"]));

                bool takePic = new AppCode.CreateDir().EqualWH(userPortrait, 45, 45);
                if (takePic)
                {
                    userPortrait= new AppCode.CreateDir().ReDraw(45, 45, userPortrait);
                }

                strli.AppendFormat(Cache["user_VisitIn"].ToString(), "/home/index.aspx?UserID=" + dtFrdIn.Rows[i]["FUserVisitor"],Jy123.Common.Input.GetSubString(dtFrdIn.Rows[i]["UserName"].ToString(),8), userPortrait);
            }
            strVisitIn_ul = strVisitIn_ul.Replace("$VisitIn$", strli.ToString());
            return strVisitIn_ul;
        }
        /// <summary>
        /// 可能认识的人
        /// </summary>
        /// <param name="userID">被查询用户的ID</param>
        /// <returns>string</returns>
        private string ListCongnition(int userID)
        {
            string congnition = Cache["user_congnition"].ToString();
            Jy123.BLL.User.Friend bllUserFrd = new Jy123.BLL.User.Friend();
            DataTable dtFrdCongnition = bllUserFrd.FriendCongnition(cpage, pagesize, userID, out count).Tables[0];
            StringBuilder strCongnili = new StringBuilder();
            for (int i = 0; i < dtFrdCongnition.Rows.Count; i++)
            {
                //根据用户ID判断用户是否有头像,如果没有头像就返回默认头像地址
                string userPortrait = new Jy123.BLL.User.SPace().DefaultPortrait(Convert.ToInt32(dtFrdCongnition.Rows[i]["ID"]));
                bool takePic = new AppCode.CreateDir().EqualWH(userPortrait, 45, 45);
                if (takePic)
                {
                    userPortrait = new AppCode.CreateDir().ReDraw(45, 45, userPortrait);
                }

                strCongnili.AppendFormat(Cache["user_friendlist"].ToString(), dtFrdCongnition.Rows[i]["UserName"], userPortrait,
                    dtFrdCongnition.Rows[i]["ID"], Common.Input.GetSubString(dtFrdCongnition.Rows[i]["UserName"].ToString(), 8));
            }
           return congnition = congnition.Replace("$VisitIn$", strCongnili.ToString());
        }

        /// <summary>
        /// 页面：我的好友列表
        /// </summary>
        /// <param name="userID">当前用户ID</param>
        /// <param name="sbHtml">外部大StringBuilder</param>
        public string PageMyFriendList(int userID, StringBuilder sbHtml)
        {
            int cpage = 1;//起始页
            int pagesize = 30;//页记录大小
            List<int?> count;
            //我的好友列表
            Jy123.BLL.User.Friend bllUserFrd = new Jy123.BLL.User.Friend();

            string strFrd_ul = Cache["user_MyFriendList_ul"].ToString();
            DataTable dtFrd = bllUserFrd.GetFriendList(cpage, pagesize, userID, out count).Tables[0];
            StringBuilder strFrd = new StringBuilder();
            for (int i = 0; i < dtFrd.Rows.Count; i++)
            {
                //根据用户ID判断用户是否有头像,如果没有头像就返回默认头像地址
                string userPortrait = new Jy123.BLL.User.SPace().DefaultPortrait(Convert.ToInt32(dtFrd.Rows[i]["FFriend"]));
                bool takePic = new AppCode.CreateDir().EqualWH(userPortrait, 45, 45);
                if (takePic)
                {
                    userPortrait = new AppCode.CreateDir().ReDraw(45, 45, userPortrait);
                }

                strFrd.AppendFormat(Cache["user_friendlist"].ToString(), dtFrd.Rows[i]["UserName"],
                    userPortrait, dtFrd.Rows[i]["FFriend"], Common.Input.GetSubString(dtFrd.Rows[i]["UserName"].ToString(), 8));
            }
            strFrd_ul = strFrd_ul.Replace("$MyFriendList$", strFrd.ToString());
            return strFrd_ul;
        }

        /// <summary>
        /// 别人的好友列表
        /// </summary>
        /// <param name="userID">别人的ID</param>
        /// <param name="sbHtml">外部大StringBuilder</param>
        /// <param name="boy">是否男</param>
        /// <returns></returns>
        public string PageFriendList_He_She(int userID, StringBuilder sbHtml, bool girl)
        {
            int cpage = 1;//起始页
            int pagesize = 30;//页记录大小
            List<int?> count;
            //我的好友列表
            Jy123.BLL.User.Friend bllUserFrd = new Jy123.BLL.User.Friend();
            string strFrd_ul = string.Empty;
            if (girl)
            {
                strFrd_ul = Cache["user_SheFriendList_ul"].ToString();
            }
            else
            {
                strFrd_ul = Cache["user_HeFriendList_ul"].ToString();
            }
            //string strFrd_ul = Cache["user_MyFriendList_ul"].ToString();
            DataTable dtFrd = bllUserFrd.GetFriendList(cpage, pagesize, userID, out count).Tables[0];
            StringBuilder strFrd = new StringBuilder();
            for (int i = 0; i < dtFrd.Rows.Count; i++)
            {
                //根据用户ID判断用户是否有头像,如果没有头像就返回默认头像地址
                string userPortrait = new Jy123.BLL.User.SPace().DefaultPortrait(Convert.ToInt32(dtFrd.Rows[i]["FFriend"]));
                bool takePic = new AppCode.CreateDir().EqualWH(userPortrait, 45, 45);
                if (takePic)
                {
                    userPortrait = new AppCode.CreateDir().ReDraw(45, 45, userPortrait);
                }

                strFrd.AppendFormat(Cache["user_friendlist"].ToString(), dtFrd.Rows[i]["UserName"],
                    userPortrait, dtFrd.Rows[i]["FFriend"], Common.Input.GetSubString(dtFrd.Rows[i]["UserName"].ToString(), 8));
            }
            strFrd_ul = strFrd_ul.Replace("$MyFriendList$", strFrd.ToString());
            return strFrd_ul;
        }
    }
}